#include "omnibox.h"

#include <QPushButton>
#include <QHBoxLayout>
#include <QKeyEvent>

#include "settings.h"

Omnibox::Omnibox(QWidget *parent) :
    QWidget(parent)
{
    signalMapper = new QSignalMapper(this);
    QGridLayout *layout = new QGridLayout(this);
    layout->setSpacing(5);

    QSettings *settings = Settings::getInstance();
    setMaximumSize(10000, settings->value("globals/button_height").toInt());
    //setMinimumSize(BUTTON_WIDTH * 4 + BUTTON_HMARGIN * 4, BUTTON_HEIGHT * 5 + BUTTON_VMARGIN * 5);

    QHBoxLayout *leLayout = new QHBoxLayout();
    leLayout->setContentsMargins(0,0,0,0);
    leLayout->setMargin(0);
    leLayout->setSpacing(0);

    lblMode = new QLabel(this);
    leLayout->addWidget(lblMode);

    le = new QLineEdit(this);
    le->setMaximumHeight(settings->value("globals/button_height").toInt());
    le->setMaxLength(20);
    connect(le, SIGNAL(textChanged(QString)), this, SIGNAL(inputChanged(QString)) );

    leLayout->addWidget(le);
    //layout->addWidget(le,0,0,1,3);

    layout->addLayout(leLayout, 0, 0, 1, 3);

    // must be CHANGED to corrent detect position
    lblMode->setText("-");
    lblMode->setText("");

    setFocusProxy(le);
    this->installEventFilter(this);
}

void Omnibox::setEchoMode(QLineEdit::EchoMode mode){
    le->setEchoMode(mode);
}

void Omnibox::setModeLabel(const QString &str){
    lblMode->setText(str);
}


QString Omnibox::getText(){
    return le->text();
}

void Omnibox::clearText(){
    le->setText("");
}


bool Omnibox::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

        if(keyEvent->key()==Qt::Key_Enter || keyEvent->key()==Qt::Key_Return){
            emit inputCommited(le->text());
            return true;
        }
    }

    return QWidget::eventFilter(obj, event);
}
